package Text3;

public class Solution {
    class ListNode{
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val,ListNode next) { this.val = val; this.next = next; }
    }

    public ListNode FindKthToTail(ListNode head,int k) {
        if(head==null||k<=0){
            return null;
        }
        ListNode slow=head;
        ListNode fast=head;
        while(k-1>0){
            fast=fast.next;
            if(fast==null){
                return null;
            }
            k--;
        }
        while(fast!=null&&fast.next!=null){
            fast=fast.next;
            slow=slow.next;
        }
        return slow;
    }

    public ListNode mergeTwoLists(ListNode head1, ListNode head2) {
        if(head1==null){
            return head2;
        }
        if(head2==null){
            return head1;
        }
        ListNode listNode = new ListNode();
        ListNode cur=listNode;
        while(head1!=null&&head2!=null){
            if(head1.val<head2.val){
                cur.next=head1;
                head1=head1.next;
            }else{
                cur.next=head2;
                head2=head2.next;
            }
            cur=cur.next;
        }
        if(head1==null){
            cur.next=head2;
        }else{
            cur.next=head1;
        }
        return listNode.next;
    }
}
